package com.xyzwps.paimon.furina.modules.auth.entity

import com.xyzwps.paimon.furina.common.DateTimeUtil
import com.xyzwps.paimon.furina.common.value.Phone
import org.jetbrains.exposed.sql.insertAndGetId
import org.jetbrains.exposed.sql.select
import org.springframework.stereotype.Repository
import java.sql.SQLIntegrityConstraintViolationException

@Repository
class UserAccountsRepository {

    private val t = UserAccount.Companion.TABLE

    fun insert(accountPhone: Phone): UserAccountInsertResult {
        try {
            val id = t.insertAndGetId {
                it[phone] = accountPhone.value
                it[locked] = false
                it[disabled] = false
                it[createTime] = DateTimeUtil.currentLocalDateTime()
                it[updateTime] = DateTimeUtil.currentLocalDateTime()
            }
            return UserAccountInsertOK(id.value)
        } catch (e: Exception) {
            if (e is SQLIntegrityConstraintViolationException) {
                return UserAccountDuplicated
            }
            throw e;
        }
    }

    fun findByPhone(phone: Phone): UserAccount? = t
        .select { UserAccount.Companion.TABLE.phone eq phone.value }
        .map { UserAccount(it) }
        .firstOrNull()
}